package com.zero.manager.service;

import com.zero.manager.common.AuthAccess;
import com.zero.manager.entity.User;
import com.zero.manager.exception.ServiceException;
import com.zero.manager.mapper.UserMapper;
import com.zero.manager.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 功能：用户表的所有业务功能
 * 作者：zero
 * 日期：2024/9/4 19:15
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public void insertUser(User user) {
        userMapper.insert(user);
    }

    public void updateUser(User user) {
        userMapper.update(user);
    }

    public void deleteUser(Integer id) {
        userMapper.delete(id);
    }

    public List<User> list() {
        return userMapper.list();
    }


    public void deleteByIds(List<Integer> ids) {
        for (Integer id : ids) {
            userMapper.delete(id);
        }
    }

    public List<User> listLike(String name) {
        return userMapper.listLike(name);
    }

    public List<User> byPage(String username, String name, Integer pageNum, Integer pageSize) {
        pageNum = (pageNum - 1) * pageSize;
        return userMapper.listPage(username, name, pageNum, pageSize);
    }

    public Integer getTotal(String username, String name) {
        return userMapper.getTotal(username, name);
    }

    public User login(User user) {
        User dbUser = userMapper.selByName(user.getUsername());
        if (dbUser == null) {
            //弹出一个自定义异常
            throw new ServiceException("不存在该用户，请更换其他用户名");
        }
        if (!Objects.equals(dbUser.getPassword(), user.getPassword())) {
            throw new ServiceException("当前用户的密码错误");
        }
        //生成Token
        String token = TokenUtils.createToken(dbUser.getId().toString(), dbUser.getPassword());
        dbUser.setToken(token);
        return dbUser;
    }

    public void register(User user) {
        if (userMapper.selByName(user.getUsername()) != null) {
            throw new ServiceException("该用户名已存在，请更换其他用户名");
        }
        user.setName(user.getUsername());
        userMapper.insert(user);
    }
}
